/*
 * ClientListener.java
 *
 * Created on August 11, 2006, 4:42 PM
 *
 */
package org.letva.copie.subserver.listeners;

import java.io.*;
import java.net.*;
import org.letva.copie.subserver.*;
import org.letva.copie.subserver.threads.ClientThread;

/**
 *
 * @author Vuk Nikolic
 */
public class ClientListener extends Thread {

	/** Creates a new instance of ClientListener */
	public ClientListener(SubServer ss) {
		mySubServer = ss;
		mySubServer.writeLog("ClientListener created.");
	}

	public void run() {
		// prvo da napravimo serverski socket
		try {
			serverSocket = new ServerSocket(mySubServer.getClientPort());
			mySubServer.writeLog("ClientListener: Server socket created.");
			// napravili smo serverski socket
		} catch (IOException e) {
			// posto nije uspeo da otvori port za cliente, da bi aktivirali dugme
			// za aktiviranje moram da gasimo i subServerListener
			mySubServer.writeLog("ClientListener: ERROR: cannot create ServerSocket.");
			mySubServer.stopSubServerListener();
			mySubServer.getMyWindow().setActivateSubServerItem(true);
			theEnd = true;
			mySubServer.getMyWindow().setDialogException("Connection Error", "Cannot connect to port: " + mySubServer.getClientPort());
		}

		// e sada da prihvatimo nove konekcije
		while (!theEnd) {
			try {
				socket = serverSocket.accept(); // blokira se dok neko ne uspostavi vezu
				mySubServer.writeLog("ClientListener: New client connected.");

				// cim je prosao accept znaci neko hoce da uspostavi vezu
				Thread t = new ClientThread(socket, mySubServer);

				mySubServer.incActiveClientThreads();
				t.start();
			} catch (SocketException ex) {
				mySubServer.writeLog("ClientListener: SocketExcpetion: " + ex);
				mySubServer.getMyWindow().setDialogException("Connection Error", "Connection problems with client");
			} catch (IOException ex) {
				mySubServer.writeLog("ClientListener: IOException: " + ex);
				mySubServer.getMyWindow().setDialogException("Connection Error", "Problems with input/output operations");
			}
		}
		mySubServer.writeLog("ClientListener: end run");
		try {
			if (serverSocket != null) {
				serverSocket.close();
			}
			if (socket != null) {
				socket.close();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}

	}

	public void stopClientListener() {
		theEnd = true;
	}
	boolean theEnd = false;
	// soket ka novom clientu
	private Socket socket = null;
	// serverski soket za klijenta
	private ServerSocket serverSocket = null;
	private SubServer mySubServer = null;
}
